﻿using INTEX.DataBase;
using INTEX.DataBase.Tools;
using ReflectionStudio.Core.Events;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.OracleClient;
using System.Linq;
using System.Text;
using System.Windows;
using WPFExcelReport.Helpers;
namespace WPFExcelReport
{
    public partial class YCAFDPLANData : BaseFunction
    {
        ApplicationBase app
        {
            get
            {
                return ApplicationBase.Instance;
            }
        }
        public INTEXDBC INTEXDBC
        {
            get
            {
                return app.INTEXDBC;
            }
        }
        public string UserID
        {
            get
            {
                return app.User;
            }
        }
        YCAAUTOEKData doc;
        SETINTEXDB INTEXDB = new SETINTEXDB();        
        public YCAFDPLANData()
            : base()
        {
        }
        public YCAFDPLANData(OracleConnection _OracleDB, IntexReptServBLClient _proxy, string userID = "        ")
            : base(_OracleDB, _proxy, userID)
        {
            Helper.GetDate(ref date, ref year, ref month, ref day);
        }
        public YCAFDPLANData(Dictionary<string, object> DicGlobalPara)
            : base(DicGlobalPara)
        {
            Helper.GetDate(ref date, ref year, ref month, ref day);
        }
        public DataSet SetUpUI()
        {
            DataSet SReturn = new DataSet();
            DataSet SResult = new DataSet();
            DataRow dwData = null;
            try
            {
                dwData = INTEXDB.ICC_SECTION.NewRow();
                dwData["SDSA"] = "0247";
                SResult = INTEXDBC.QuerySDDAT(dwData, 3);
                SResult.Tables[0].TableName = "ICC_SECTION";
                foreach (DataRow row in SResult.Tables[0].Rows)
                {
                    row["SDDATEN"] = Helpers.Helper.GetGB2312Value(row["SDDATEN"].ToString());
                }
                SReturn.Merge(SResult);
                dwData = INTEXDB.LIEFDAT.NewLIEFDATRow();
                dwData["LSMANDANT"] = "00";
                dwData["LSGRSCHL"] = "ACC";
                SResult = INTEXDBC.QueryLIEFDAT(dwData, 3);
                foreach (DataRow rx in SResult.Tables[0].Rows)
                {
                    rx["LSNAME1"] = Helper.GetGB2312Value(rx["LSNAME1"].ToString().Trim());
                }
                SReturn.Merge(SResult);
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
            return SReturn;
        }
        public void Refresh()
        {
            INTEXDBC.UpdateFSEINK(null, "", 2);//更新计价单位
            INTEXDBC.InsertICC_ABAUFM(null, 3);
            INTEXDBC.UpdateICC_ABAUFM(null, 11);//品名描述
            INTEXDBC.UpdateICC_ABAUFM(null, 12);//颜色描述
            INTEXDBC.UpdateICC_ABAUFM(null, 221);//标准价格
            INTEXDBC.UpdateICC_ABAUFM(null, 241);//标准价格
            INTEXDBC.UpdateICC_ABAUFM(null, 251);//标准价格
            INTEXDBC.UpdateICC_ABAUFM(null, 261);//标准价格
        }
        public DataSet LoadGXDECKData(DataRow dwInput, string sections)
        {
            DataSet SReturn = new DataSet();
            DataSet SResult = new DataSet();
            DataRow dwData = null;
            double wastageek = 0, prodplanrate = 0;
            try
            {
                //刷新数据，若有新的需求则插入
                if (sections.Trim() == "")
                {
                    //MessageBox.Show("请选择区段!");
                    //return SReturn;
                }
                ///读取汇总信息          
                string art = dwInput["ART"].ToString();

                dwData = INTEXDB.FDECK.NewRow();
                dwData["FDMANDANT"] = "00";
                dwData["FDSA"] = "V";
                dwData["FDTYP"] = "B";
                dwData["FDAUFKRS"] = dwInput["KRS"];
                dwData["FDAUFLFD"] = dwInput["LFD"];
                if (dwData["FDAUFLFD"].ToString().Trim() == "000000")
                    dwData["FDAUFLFD"] = "0";
                dwData["FDART"] = art;
                dwData["FDFILLER"] = dwInput["FART"];
                SResult = INTEXDBC.QueryICC_ABAUFM(dwData, 911);
                if (SResult.Tables.Count > 0)
                {
                    SResult.Tables[0].TableName = "ICC_XDECK";
                }
                foreach (DataRow row in SResult.Tables[0].Rows)
                {
                    row["PLANRATE"] = prodplanrate;
                    row["WASTAGEEK"] = wastageek;
                    row["REQ"] = Convert.ToDouble(row["REQ"].ToString()) * (1 + prodplanrate * 0.01) * (1 + wastageek * 0.01);
                }

                SReturn.Merge(SResult);
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
            return SReturn;
        }
        public DataSet LoadXDECKData(DataRow dwInput, bool IsPlanned, string sections, string EKPBEKZ)
        {
            DataSet SReturn = new DataSet();
            DataSet SResult = new DataSet();
            DataSet STemp = new DataSet();
            DataRow dwData = null;
     
            try
            {
                //MBST EKPOS MDECK ABPOS ICC_ABAUFM
                string client = dwInput["MANDANT"].ToString();
                string wakz = " ";
                string art = dwInput["ART"].ToString();
                string var = Left(dwInput["VAR"].ToString() + "   ", 3);
                string color = dwInput["COLOR"].ToString();
                string size = dwInput["ASIZE"].ToString();
                string CREF = dwInput["CREF"].ToString();
                string abpart = dwInput["ABPART"].ToString();
                //读取库存
                dwData = INTEXDB.FBST.NewRow();
                dwData["FBMANDANT"] = client;
                dwData["FBART"] = art;
                dwData["FBVAR"] = var;
                dwData["FBFARBE"] = color;
                dwData["FBGROE"] = size;
                SResult = INTEXDBC.QueryICC_FBST(dwData, 2);
                SResult.Tables[0].TableName = "ICC_STOCK";
                SReturn.Merge(SResult);
                //读取采购              
                art = Left(art + "                                              ", 20);
                color = Left(color + "                                              ", 10);
                
                if (UserID.Trim() == "YCAV")
                {
                    SResult = INTEXDBC.QueryICC_EKPOS(client, wakz, art, var, color, size, EKPBEKZ, 1);
                }
                else
                {
                    SResult = INTEXDBC.QueryICC_EKPOS(client, wakz, art, var, color, size, EKPBEKZ, 6);
                }
                SReturn.Merge(SResult);
                //读取锁定数量
                CheckLockedQty(ref SReturn, dwInput);
                //读取明细
                dwData = INTEXDB.ICC_ABAUFM.NewRow();
                dwData["ABAMANDANT"] = client;
                dwData["ABPART"] = dwInput["ABPART"];
                dwData["ABAART"] = art;
                dwData["ABAVAR"] = var;
                dwData["ABAFARBE"] = color;
                dwData["ABAGROE"] = size;
                dwData["FSSZUSCHN"] = " ";
                dwData["ABACOLORREF"] = Left(CREF + "                                                                                                                                                                             ", 100);
                dwData["ABAVKAUFKRS"] = dwInput["ABAVKAUFKRS"].ToString();
                dwData["ABAVKAUFLFD"] = dwInput["ABAVKAUFLFD"].ToString();
                dwData["ABAVKAUFPOS"] = "89";//ABAVKAUFKRS ABPSPGRD
                    
                /*   if (IsPlanned)
                   {
                       SResult = INTEXDBC.QueryICC_ABAUFM(dwData, 12);
                   }
                   else
                   {
                       SResult = INTEXDBC.QueryICC_ABAUFM(dwData, 13);
                   }
                   SReturn.Merge(SResult);

                   dwData["ABAVKAUFKRS"] = "89";//ABAVKAUFKRS ABPSPGRD*/

                SResult = INTEXDBC.QueryICC_ABAUFM(dwData, 15);
                if (SResult.Tables.Count > 0)
                {
                    SResult.Tables[0].TableName = "NC_ICC_ABAUFM";
                    SReturn.Merge(SResult);
                }

                dwData["ABPART"] = Left(abpart + "                  ", 20);
                SResult = INTEXDBC.QueryICC_ABAUFM(dwData, 17);
                if (SResult.Tables.Count > 0)
                {
                    SResult.Tables[0].TableName = "ICC_ABAUFM";
                    SReturn.Merge(SResult);
                }
                SResult = INTEXDBC.QueryABPOS(dwData, 15);
                SReturn.Merge(SResult);
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
            return SReturn;
        }
        public void CheckLockedQty(ref DataSet src, DataRow dwInput)
        {
            DataSet SResult = new DataSet();
            DataRow dwData = null;
            string client = dwInput["MANDANT"].ToString();
            string wakz = " ";
            string art = Left(dwInput["ART"].ToString() + "             ", 20);
            string var = Left(dwInput["VAR"].ToString() + "             ", 3);
            string color = Left(dwInput["COLOR"].ToString() + "        ", 10);
            string size = Left(dwInput["ASIZE"].ToString() + "          ", 7);
            dwData = INTEXDB.ICC_ABAUFM.NewRow();
            dwData["ABAMANDANT"] = client;
            dwData["ABAART"] = art;
            dwData["ABAVAR"] = var;
            dwData["ABAFARBE"] = color;
            dwData["ABAGROE"] = size;
            SResult = INTEXDBC.QueryICC_ABAUFM(dwData, 5);
            foreach (DataRow rz in SResult.Tables[0].Rows)
            {
                string sptype = rz["ABAAUFTYP"].ToString();
                switch (sptype)
                {
                    case "N":
                        break;
                    case "B":
                        var query1 = from DataRow rwz in src.Tables["ICC_STOKC"].AsEnumerable()
                                     where rwz["LO"].ToString().Trim() == rz["ABAAUFKRS"].ToString().Trim()
                                     && rwz["LB"].ToString().Trim() == rz["ABAAUFLFD"].ToString().Trim()
                                     select rwz;
                        foreach (DataRow rwz in query1)
                        {
                            rwz["QTYLOCKED"] = System.Math.Round(System.Convert.ToDouble(rz["ABAQTYALLOCATE"].ToString()), 2);
                            rwz["QTYFREE"] = System.Math.Round(System.Convert.ToDouble(rwz["QTY"].ToString()) - System.Convert.ToDouble(rwz["QTYLOCKED"].ToString()), 2);
                        }
                        break;
                    case "P":
                        var query2 = from DataRow rwz in src.Tables["ICC_EKPOS"].AsEnumerable()
                                     where rwz["EKPAUFKRS"].ToString().Trim() == rz["ABAAUFKRS"].ToString().Trim()
                                     && rwz["EKPAUFLFD"].ToString().Trim() == rz["ABAAUFLFD"].ToString().Trim()
                                     && rwz["EKPAUFPOS"].ToString().Trim() == rz["ABAAUFPOS"].ToString().Trim()
                                     select rwz;
                        foreach (DataRow rwz in query2)
                        {
                            rwz["EKPQTYLOCKED"] = System.Math.Round(System.Convert.ToDouble(rz["ABAQTYRESERVE"].ToString()), 2);
                            rwz["EKPQTYFREE"] = System.Math.Round(System.Convert.ToDouble(rwz["EKPME1"].ToString()) - System.Convert.ToDouble(rwz["EKPQTYLOCKED"].ToString()), 2);
                        }
                        break;
                    default:
                        break;
                }
            }
        }
        public DataSet LoadSupplier()
        {
            DataSet SReturn = new DataSet();
            DataSet SResult = new DataSet();
            DataRow dwData = INTEXDB.LIEFDAT.NewLIEFDATRow();
            dwData["LSMANDANT"] = "00";
            SResult = INTEXDBC.QueryLIEFDAT(dwData, 3);
            SReturn.Merge(SResult);
            return SReturn;
        }
        public DataSet CreateTempEKPOS(DataTable tbEKPOS)
        {
            DataSet SReturn = new DataSet();
            DataSet SResult = new DataSet();
            DataSet STemp = new DataSet();
            List<string> listsup = new List<string>();
            ASCIIEncoding ascII = new System.Text.ASCIIEncoding();
            try
            {
                //读取MS，获取默认供应商，如果没有则是0
                string art = "", var = "", color = "", size = "";
                string supplier = "00000000";
                string procesed = "00000000;";
                listsup.Add(supplier);
                /*界面：  	EKPNEUB EKPNEUDB EKPLTERM  EKPLTERM EKPMEEHFKT EKPME1 EKPSMENGE  EKPPRME EKPPREH  	
                 * EKPARTGR EKPART 	EKPVAR 	EKPFARBE           	EKPDESS          	EKPCOL
                 * EKPBESCH    	EKPZUSTAND       	EKPGROE
                 此处        	EKPAUFGRP BE	EKPAUFART  
8	
000001000000	EKPMEEHFKT
*/
                foreach (DataRow rw in tbEKPOS.Rows)
                {
                    int leadtime = 0;
                    string csupplier = rw["EKPLIEFNR"].ToString();
                    rw["EKPARTGR"] = "5";
                    rw["EKPAUFGRP"] = "B";
                    rw["EKPAUFART"] = "BE";
                    art = rw["EKPART"].ToString();// ascII.GetString((byte[])rw["EKPART"]);
                    var = rw["EKPVAR"].ToString();// ascII.GetString((byte[])rw["EKPVAR"]);
                    color = rw["EKPFARBE"].ToString();
                    size = rw["EKPGROE"].ToString();
                    DataRow rms = INTEXDB.FSEINK.NewFSEINKRow();
                    rms["FEMANDANT"] = "00";
                    rms["FEART"] = Left(art, 20);
                    rms["FEVAR"] = Left(var, 2);
                    STemp = INTEXDBC.QueryFSEINK(rms, 2);
                    string pcolor = "";
                    string psize = "";
                    double colorp = 0;
                    double sizep = 0;
                    double exactprice = 0;
                    double price = 0;
                    string filter = "";
                    DataRow[] rows;
                    DataRow rprice = null;
                    //order by FEART DESC, FEFARBE DESC,FEGROE DESC
                    filter = "FEFARBE='" + Left(color, 10) + "' AND FEGROE='" + Left(size, 7) + "'";
                    rows = STemp.Tables[0].Select(filter);
                    if (rows.Length > 0)
                    {
                        rprice = rows[0];
                    }
                    if (rprice == null)
                    {
                        if (color.Trim() != "")
                        {

                            filter = "FEFARBE='" + Left(color, 10) + "'";
                            rows = STemp.Tables[0].Select(filter);
                            if (rows.Length > 0)
                            {
                                rprice = rows[0];
                            }
                        }
                    }
                    if (rprice == null)
                    {
                        if (size.Trim() != "")
                        {
                            filter = "FEGROE='" + Left(size, 7) + "'";
                            rows = STemp.Tables[0].Select(filter);
                            if (rows.Length > 0)
                            {
                                rprice = rows[0];
                            }
                        }
                    }
                    //FSUEBM

                    if (rprice == null)
                    {
                        rows = STemp.Tables[0].Select();
                        if (rows.Length > 0)
                        {
                            rprice = rows[0];
                        }
                    }
                    if (rprice != null)
                    {
                        supplier = rprice["FELIEFNR"].ToString();
                        double unit = System.Convert.ToDouble(rprice["FEMINBSLM1"].ToString());
                        price = System.Convert.ToDouble(rprice["FEPREIS1"].ToString()) / unit;
                        if (csupplier == "00000000")
                        {
                            rw["EKPLIEFNR"] = supplier;
                        }
                        rw["EKPPRME"] = Right("0000000000" + price * 10, 10);
                        //rw["EKPPREH"] = "PCS";
                        rw["EKPMEEHFKT"] = "000001000000";
                        leadtime = System.Convert.ToInt16(rprice["FELIEFZT"].ToString());                        
                        rw["EKPLTERM"] = GetDateAddDays(date, leadtime);
                        if (!procesed.Contains(supplier + ";"))
                        {
                            procesed += supplier + ";";
                            listsup.Add(supplier);
                        }
                        if (!procesed.Contains(csupplier + ";"))
                        {
                            procesed += csupplier + ";";
                            listsup.Add(csupplier);
                        }
                    }
                    rw["EKPLTERM"] = GetDateAddDays(date, leadtime);
                }
                foreach (string sup in listsup)
                {
                    int pos = 1;
                    string lfd = "";
                    string krs = "";
                    var query = from DataRow ekp in tbEKPOS.AsEnumerable()
                                where ekp["EKPLIEFNR"].ToString() == sup
                                select ekp;
                    foreach (DataRow ekp in query)
                    {
                        krs = ekp["EKPAUFKRS"].ToString();
                        if (lfd == "")
                        {
                            lfd = GetAUFLFD(krs, "EKAUFTR");
                        }
                        ekp["EKPAUFLFD"] = lfd;
                        ekp["EKPAUFPOS"] = Right("000" + pos, 3);
                        pos++;
                    }
                } 
                foreach (DataRow ekp in tbEKPOS.Rows)
                {
                    if (ekp["EKPAUFLFD"].ToString().Trim() == "" || ekp["EKPAUFLFD"].ToString().Trim() == "000000")
                        throw new Exception("出现采购单号码空号，请立即通知管理员");
                }
                //赋予供应商
                //根据供应商情况，组合采购单，产生EKKOPF
                SResult.Merge(tbEKPOS);
                SResult.Tables[0].TableName = "ICC_EKPOS";
                SReturn.Merge(SResult);
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
            return SReturn;
        }
        public DataSet ITXPurchase(SETINTEXDB SetData, string sections, bool IsAutoAllocation, bool IsAutoSplit)
        {
            DataSet SetTmp = new DataSet();
            DataSet SReturn = new DataSet();
            try
            {
                string xml = @"C:\IntexReport\Data\YCAATEK\01Temp\EK" + DateTime.Now.ToFileTime().ToString() + ".XML";
                SetTmp.Clear();
                DataTable tbtemp = SetData.ICC_EKPOS.Copy();
                tbtemp.TableName = "EKPOS_EXT";
                foreach (DataRow rw in tbtemp.Rows)
                {
                    rw["EKPME1"] = System.Math.Round(System.Convert.ToDecimal(rw["EKPME1"].ToString()) * 100, 0);
                    rw["EKPWE1"] = System.Math.Round(System.Convert.ToDouble(rw["EKPME1"].ToString())
                        * System.Convert.ToDouble(rw["EKPPRME"].ToString())
                        * 0.001, 0);
                }
                SetTmp.Merge(tbtemp);
                SetTmp.WriteXml(xml);
                Send2Intex(dicParamater);
                tbtemp.TableName = "ICC_EKPOS";
                SReturn.Merge(tbtemp);
                foreach (DataRow row in tbtemp.Rows)
                {
                    row["EKPQTYFREE"] = System.Convert.ToDouble(row["EKPME1"].ToString()) * 0.01;
                    if (IsAutoAllocation)
                    {
                        BatchReservation(row, SetData, IsAutoSplit);
                        row["EKPBEKZ"] = "N";
                        INTEXDBC.UpdateEKPOS(row, 3);
                    }
                }
                DataRow dwData = INTEXDB.EKKOPF.NewRow();
                bool IsValid = true;
                string processed = "";
                foreach (DataRow rw in tbtemp.Rows)
                {
                    string mandant = "", krs = "", lfd = "";
                    krs = rw["EKPAUFKRS"].ToString();
                    lfd = rw["EKPAUFLFD"].ToString();
                    if (processed.Contains(krs + lfd + ";"))
                        continue;
                    processed += krs + lfd + ";";
                    doc.ValidateEK(rw, ref IsValid);
                }
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
            finally
            {
                EventDispatcher.Instance.RaiseStatus("全部完成", StatusEventType.StopProgress);
            }
            return SReturn;
        }
        public string DeleteReservation(SETINTEXDB SetData)
        {
            string orders = "";
            try
            {
                foreach (DataRow row in SetData.ICC_ABAUFM.Rows)
                {
                    if (row["ABAAUFTYP"].ToString().Trim() != "N")
                        continue;
                    row["ABAAUFTYP"] = "X";
                    INTEXDBC.UpdateICC_ABAUFM(row, 5);
                    orders += row["ABAAUFKRS"].ToString() + row["ABAAUFLFD"].ToString();
                    /*INTEXDBC.DeleteICC_ABAUFM("", "", "", "", row, 4);
                    DataRow XD = SetData.FDECK.NewRow();
                    XD["FDMANDANT"] = row["ABAMANDANT"];
                    XD["FDAUFKRS"] = row["ABAVKAUFKRS"];
                    XD["FDAUFLFD"] = row["ABAVKAUFLFD"];
                    XD["FDAUFPOS"] = row["ABAVKAUFPOS"];
                    XD["FDART"] = row["ABAART"];
                    XD["FDVAR"] =Left( row["ABAVAR"].ToString(),2);
                    XD["FDFARBE"] = row["ABAFARBE"];
                    XD["FDGROE"] = row["ABAGROE"];
       
                    INTEXDBC.DeleteFDECK(XD, 2);*/
                }
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
            return orders;
        }
        public void BatchReservation(DataRow dwITXSOURCE, SETINTEXDB SetData, bool IsAutoSplit)
        {
            string client = "", art = "", var = "", color = "", size = "";
            string pSType = "B";
            DataSet SResult = new DataSet();
            DataRow dwTemp;
            string UM = "PCS";
            string CREF = "";
            string abpart = "";
            try
            {
                if (dwITXSOURCE.Table.TableName.Contains("EKPOS"))
                {
                    pSType = "P";
                }
                if (pSType == "P")
                {
                    client = "00";
                    art = dwITXSOURCE["EKPART"].ToString();
                    var = dwITXSOURCE["EKPVAR"].ToString();
                    color = dwITXSOURCE["EKPFARBE"].ToString();
                    size = dwITXSOURCE["EKPGROE"].ToString();
                    UM = dwITXSOURCE["EKPMEEH"].ToString().Trim();
                    CREF = dwITXSOURCE["EKPLSGRPBEZ"].ToString();
                    abpart = dwITXSOURCE["ABPART"].ToString();
                }
                dwTemp = INTEXDB.ICC_ABAUFM.NewRow();
                dwTemp["ABAMANDANT"] = client;
                dwTemp["ABAART"] = Left(art + "                                    ", 20);
                dwTemp["ABAVAR"] = Left(var + "                                    ", 3);
                dwTemp["ABAFARBE"] = color;
                dwTemp["ABAGROE"] = Left(size + "   ", 7);
                dwTemp["ABACOLORREF"] = Left(CREF + "                                                                                                                                                                             ", 100);
                dwTemp["ABAVKAUFKRS"] = dwITXSOURCE["EKPFAUFKRS"].ToString();
                dwTemp["ABAVKAUFLFD"] = dwITXSOURCE["EKPFAUFLFD"].ToString();
                //dwTemp["ABAVKAUFPOS"] = "89";//ABAVKAUFKRS ABPSPGRD                
                dwTemp["ABAVKAUFPOS"] = "99";//ABAVKAUFKRS ABPSPGRD                
                dwTemp["ABPART"] = Left(abpart + "                  ", 20);
                dwTemp["FSSZUSCHN"] = " ";
                SResult = INTEXDBC.QueryICC_ABAUFM(dwTemp, 17);
                SETINTEXDB SAB = new SETINTEXDB();
                SAB.Merge(SResult);
                if (SResult.Tables.Count > 0)
                {
                    bool lastrow = false;
                    int count = SResult.Tables[0].Rows.Count;
                    int rown = 0;
                    decimal ratio = 1;
                    if (IsAutoSplit)
                    {
                        decimal pSQTY = System.Convert.ToDecimal(dwITXSOURCE["EKPQTYFREE"].ToString());//可用数量
                        ratio = AutoSplit(pSQTY, SResult.Tables[0]);
                    }
                    foreach (DataRow row in SResult.Tables[0].Rows)
                    {
                        rown++;
                        if (rown == count)
                        {
                            lastrow = true;
                        }
                        Reservation(row, dwITXSOURCE, SAB, lastrow, ratio);
                    }
                }
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }
        private decimal AutoSplit(decimal qty, DataTable tbDECK)
        {
            decimal qreq = 0;
            decimal ratio = 1;
            var qxd = from XD in tbDECK.AsEnumerable()
                      group XD by new
                      {
                          TYP = XD["ABAAUFTYP"].ToString(),
                      }
                          into g
                          select new
                          {
                              KEY = g.Key,
                              ABARESMG = g.Sum(XD => Convert.ToDecimal(XD.Field<Decimal>("ABARESMG"))),
                          };
            foreach (var XD in qxd)
            {
                if (XD.KEY.TYP.ToString() == "N")
                {
                    qreq = System.Math.Round(XD.ABARESMG, 0);
                }
            }
            if (qreq > 0)
            {
                ratio = System.Math.Round(qty / qreq, 2);
            }

            return ratio;
        }
        public void Reservation(DataRow dwITXXDECK, DataRow dwITXSOURCE, SETINTEXDB SetData, bool lastrow, decimal ratio)
        {
            DataSet SReturn = new DataSet();
            DataSet SResult = new DataSet();
            DataSet STemp = new DataSet();
            string pSKRS = "", pSLFD = "", pSPOS = "";
            string pSType = "B";
            decimal pSQTY = 0;
            decimal QTY = 0;
            try
            {
                if (dwITXSOURCE == null)
                    return;
                if (dwITXSOURCE.Table.TableName.Contains("EKPOS"))
                {
                    pSType = "P";
                }
                if (pSType == "P")
                {
                    pSKRS = dwITXSOURCE["EKPAUFKRS"].ToString();
                    pSLFD = dwITXSOURCE["EKPAUFLFD"].ToString();
                    pSPOS = dwITXSOURCE["EKPAUFPOS"].ToString();
                    pSQTY = System.Convert.ToDecimal(dwITXSOURCE["EKPQTYFREE"].ToString());//可用数量
                    QTY = System.Convert.ToDecimal(dwITXSOURCE["EKPME1"].ToString());//采购数量
                }
                if (pSType == "B")
                {
                    pSKRS = dwITXSOURCE["LO"].ToString();
                    pSLFD = dwITXSOURCE["LB"].ToString();
                    pSPOS = "000";
                    pSQTY = System.Convert.ToDecimal(dwITXSOURCE["QTYFREE"].ToString());//可用数量
                    QTY = System.Convert.ToDecimal(dwITXSOURCE["QTY"].ToString());//库存数量
                }
                DataRow row = dwITXXDECK;
                string krs = row["ABAVKAUFKRS"].ToString();
                string lfd = row["ABAVKAUFLFD"].ToString();
                string pos = row["ABAVKAUFPOS"].ToString();
                string mart = row["ABAART"].ToString();
                string mvar = row["ABAVAR"].ToString();
                string mfarbe = row["ABAFARBE"].ToString();
                string msize = row["ABAGROE"].ToString();
                string ABAID = row["ABAID"].ToString();
                if (pSType.Trim() == "")
                    return;
                if (pSQTY <= 0)
                    return;
                var query1 = from rx in SetData.ICC_ABAUFM.AsEnumerable()
                             where rx["ABAID"].ToString() == ABAID
                             select rx;
                foreach (DataRow rx in query1)
                {
                    ///2.	若可用数量>需求数量，则用留位数量满足需求，不关闭需求
                    ///3.	若可用数量<需求数量，在不允许执行
                    ///
                    decimal rqty = System.Convert.ToDecimal(rx["ABARESMG"].ToString());//需求数量

                    string atyp = rx["ABAAUFTYP"].ToString().Trim();
                    string akrs = rx["ABAAUFKRS"].ToString().Trim();
                    string alfd = rx["ABAAUFLFD"].ToString().Trim();
                    string apos = rx["ABAAUFPOS"].ToString().Trim();
                    if (rx["ABAAUFTYP"].ToString().Trim() != "N")
                    {
                        continue;
                    }
                    if (atyp.Trim() == pSType.Trim()
                        && akrs.Trim() == pSKRS.Trim()
                        && alfd.Trim() == pSLFD.Trim()
                        && apos.Trim() == pSPOS.Trim()
                        )
                    {
                        return;
                    }
                    rqty = System.Math.Round(rqty * ratio);
                    rx["ABARESMG"] = rqty;
                    decimal qtyre = System.Convert.ToDecimal(rx["ABAQTYRECEIVED"].ToString());
                    if (qtyre > 0)//通过此标志，判断是否是补充采购。
                    {
                        rx["ABAQTYRECEIVED"] = 0;
                        rx["ABARESMG"] = 0;
                        INTEXDBC.UpdateICC_ABAUFM(rx, 13);
                    }
                    /*if (ratio < 1
                        || ratio > 1)
                    {
                        DataRow XD = SetData.FDECK.NewRow();
                        XD["FDMANDANT"] = "00";
                        XD["FDAUFKRS"] = krs;
                        XD["FDAUFLFD"] = lfd;
                        XD["FDAUFPOS"] = pos;
                        XD["FDART"] = mart;
                        XD["FDVAR"] = Left(mvar, 2);
                        XD["FDFARBE"] = mfarbe;
                        XD["FDGROE"] = msize;
                        //decimal mqty = System.Convert.ToDecimal(XD["FDMENGE"].ToString());
                        XD["FDMENGE"] = System.Math.Round(rqty);
                        INTEXDBC.UpdateFDECK(XD, "", 2);
                    }*/
                    if (pSQTY >= rqty)
                    {
                        #region====数量足够=====
                        rx["ABAAUFTYP"] = pSType;
                        rx["ABAAUFKRS"] = pSKRS;
                        rx["ABAAUFLFD"] = pSLFD;
                        rx["ABAAUFPOS"] = pSPOS;
                        pSQTY -= rqty;
                        switch (pSType)
                        {
                            case "B":
                                rx["ABAQTYALLOCATE"] = rqty;
                                rx["ABAQTYRESERVE"] = 0;
                                if (dwITXSOURCE.Table.Columns.Contains("QTYFREE"))
                                {
                                    dwITXSOURCE["QTYFREE"] = pSQTY;
                                    dwITXSOURCE["QTYLOCKED"] = QTY - pSQTY;
                                }
                                break;
                            case "P":
                                rx["ABAQTYALLOCATE"] = 0;
                                rx["ABAQTYRESERVE"] = rqty;
                                if (dwITXSOURCE.Table.Columns.Contains("EKPQTYFREE"))
                                {
                                    dwITXSOURCE["EKPQTYFREE"] = pSQTY;
                                    dwITXSOURCE["EKPQTYLOCKED"] = System.Math.Round(QTY - pSQTY);
                                }
                                if (lastrow)
                                {
                                    rx["ABAQTYALLOCATE"] = 0;
                                    rx["ABAQTYRESERVE"] = rqty + pSQTY;
                                    if (dwITXSOURCE.Table.Columns.Contains("EKPQTYFREE"))
                                    {
                                        dwITXSOURCE["EKPQTYFREE"] = 0;
                                        dwITXSOURCE["EKPQTYLOCKED"] = QTY;
                                    }
                                }
                                break;
                            default:
                                break;
                        }
                        INTEXDBC.UpdateICC_ABAUFM(rx, 10);//这里是满足需求的关系，若是部分满足，则拆分数量

                        #endregion
                    }
                    else
                    {
                        #region====数量不足=====
                        //MessageBox.Show("本次采购仅仅满足了部分数量，是吗?");
                        EventDispatcher.Instance.RaiseStatus("本次采购仅仅满足了部分数量" + pSKRS + pSLFD + pSPOS, StatusEventType.StopProgress);
                        rx["ABAAUFTYP"] = pSType;
                        rx["ABAAUFKRS"] = pSKRS;
                        rx["ABAAUFLFD"] = pSLFD;
                        rx["ABAAUFPOS"] = pSPOS;
                        rx["ABARESMG"] = pSQTY;
                        switch (pSType)
                        {
                            case "B":
                                rx["ABAQTYALLOCATE"] = pSQTY;
                                rx["ABAQTYRESERVE"] = 0;
                                if (dwITXSOURCE.Table.Columns.Contains("QTYFREE"))
                                {
                                    dwITXSOURCE["QTYFREE"] = 0;
                                }
                                dwITXSOURCE["QTYLOCKED"] = QTY;
                                break;
                            case "P":
                                rx["ABAQTYALLOCATE"] = 0;
                                rx["ABAQTYRESERVE"] = pSQTY;
                                if (dwITXSOURCE.Table.Columns.Contains("EKPQTYFREE"))
                                {
                                    dwITXSOURCE["EKPQTYFREE"] = 0;
                                }
                                dwITXSOURCE["EKPQTYLOCKED"] = QTY;
                                break;
                            default:
                                break;
                        }
                        // ABAQTYALLOCATE,ABAQTYRESERVE,ABAQTYRECEIVED,
                        INTEXDBC.UpdateICC_ABAUFM(rx, 10);//这里是满足需求的关系，若是部分满足，则拆分数量                               
                        /*DataRow ry = SetData.ICC_ABAUFM.NewRow();
                        ry.ItemArray = rx.ItemArray;
                        if (pSType == "P")
                        {
                            ry["ABARESMG"] = rqty - pSQTY;
                        }
                        if (pSType == "B")
                        {
                            ry["ABARESMG"] = (rqty - pSQTY);
                        }
                        INTEXDBC.InsertICC_ABAUFM(rx, 9);//要考虑唯一性*/
                        pSQTY = 0;
                        #endregion
                    }
                }
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
            finally
            {
                EventDispatcher.Instance.RaiseStatus("完成" + pSKRS + pSLFD + pSPOS, StatusEventType.StopProgress);
            }

        }
        public DataSet LoadABPOSData(DataRow dwInput)
        {
            DataSet SReturn = new DataSet();
            DataSet SResult = new DataSet();
            DataSet STemp = new DataSet();
            DataRow dwData = null;
            try
            {
                dwData = INTEXDB.ICC_ABAUFM.NewRow();
                dwData["ABAMANDANT"] = dwInput["ABPMANDANT"];
                dwData["ABAVKAUFKRS"] = dwInput["ABPAUFKRS"];
                dwData["ABAVKAUFLFD"] = dwInput["ABPAUFLFD"];
                dwData["ABAVKAUFPOS"] = dwInput["ABPAUFPOS"];
                SResult = INTEXDBC.QueryICC_ABAUFM(dwData, 7);
                SReturn.Merge(SResult);
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
            return SReturn;
        }
        public void Send2Intex(Dictionary<string, object> dicParamater)
        {
            try
            {
                doc = new YCAAUTOEKData(OracleDB, proxy);
                doc.AutoRun();
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }
        public void CheckData(DataSet src, ref bool IsSuccess, ref string msg)
        {
            try
            {
                DataTable tb = src.Tables["ICC_EKPOS"];
                foreach (DataRow rw in tb.Rows)
                {
                    string value = rw["EKPPRME"].ToString().Trim();
                    string order = rw["EKPAUFKRS"].ToString() + rw["EKPAUFLFD"].ToString() + rw["EKPAUFPOS"].ToString();
                    if (value == "" || value == "0")
                    {
                        msg += "请输入" + order + "价格!";
                        IsSuccess = false;
                    }
                }
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }
    }
}